package monitor

import (
	"fmt"
	"net"
	"net/http"

	"github.com/prometheus/client_golang/prometheus/promhttp"
)

type MonitorServer struct {
	httpServer *http.Server
	port       int
}

func NewMonitorServer(nameSpace string, port int, enable bool) *MonitorServer {
	retServer := MonitorServer{
		port: port,
	}
	if !enable {
		return &retServer
	}
	nameSpace = nameSpace
	mux := http.NewServeMux()
	mux.Handle("/metrics", promhttp.Handler())
	retServer.httpServer = &http.Server{
		Handler: mux,
	}
	return &retServer
}

func (s *MonitorServer) Start(enable bool) error {
	if !enable {
		return nil
	}
	if s.httpServer != nil {
		endPoint := fmt.Sprintf(":%d", s.port)
		conn, err := net.Listen("tcp", endPoint)
		if err != nil {
			return fmt.Errorf("TCP Listen failed, %s", err.Error())
		}
		go func() {
			err = s.httpServer.Serve(conn)
			if err != nil {
				fmt.Errorf("http server failed , %s", err.Error())
			}
		}()
	}
	return nil
}
